package cn.spiral.qz_job.jobclass;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.spiral.qz_job.dao.QzJobDao;
import cn.spiral.qz_job.entity.QzJob;
import cn.spiral.qz_job.service.QzJobService;
import cn.spiral.qz_job.service.impl.QzJobServiceImpl;

public class AddJob extends QuartzJobBean{

	@Override
	protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		
		//从JobDataMap中取出任务名字和service
		JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
		String jobName=jobDataMap.getString("jobName");
		QzJobService qzJobService=(QzJobService) jobDataMap.get("qzJobService");
		//通过访问数据库取出任务相关的信息
		QzJob job = qzJobService.findJobByName(jobName);
		//如果为空,说明任务表中找不到，被人为手动删除，任务结束
		if(job!=null){
			//任务处于开启状态，则执行任务
			if(job.getJobState()==job.JOB_STATE_OPEN){
				
				File excelFile=new File(job.getJobTable());
				String excelFileName = excelFile.getName();
				Workbook workbook = null;
				InputStream inputStream=null;
				OutputStream outputStream=null;
				PrintWriter writer=null;
				try {
					//没有发邮件或短信的API改用输出日志测试
					File outPutfile=new File("D:\\quartzTest\\"+job.getJobName()+".txt");
					if(!outPutfile.exists()){
						outPutfile.createNewFile();
					}
					//判断是否为03版excel
					boolean is03Excel=excelFileName.matches("^.+//.(i?)(xls)$");
				
					//获得输入流，读取表格中的内容
					inputStream=new FileInputStream(excelFile);
					outputStream=new FileOutputStream(outPutfile);
					writer=new PrintWriter(outputStream);
					workbook= is03Excel ? new HSSFWorkbook(inputStream) : new XSSFWorkbook(inputStream);
					//获得第一个工作表
					Sheet sheet=workbook.getSheetAt(0);
					//读取行，第一行为列名，第二行开始是数据，认为少于两行为无有效数据
					if(sheet.getPhysicalNumberOfRows()>1){
						for(int k=1;k<sheet.getPhysicalNumberOfRows();k++){
							
							Row row=sheet.getRow(k);
							String userName=row.getCell(0).getStringCellValue();
							String to=row.getCell(1).getStringCellValue();
							//拼接发送内容
							String content="尊敬的"+userName+"用户，"+job.getJobContent();
							//判断用手机还是用邮箱发
							if(job.getJobSendType()==job.JOB_SEND_TYPE_EMAIL){
								seandByEmail(writer, to, content);
							}else if(job.getJobSendType()==job.JOB_SEND_TYPE_PHONE){
								sendByPhone(writer, to, content);
							}
						}
					}
					job.setJobState(job.JOB_STATE_SUCCESS);
					qzJobService.update(job);
				} catch (IOException e) {
					e.printStackTrace();
					job.setJobState(job.JOB_STATE_FAIL);
					qzJobService.update(job);
				}finally {
					try {
						workbook.close();
						writer.close();
						inputStream.close();
						outputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
			}else if(job.getJobState()==job.JOB_STATE_CLOSE){//任务处于暂停状态，则不执行，并且将其状态改为失效
				job.setJobState(job.JOB_STATE_INVALI);
				qzJobService.update(job);
			}//其它状态不用执行任务，结束
		}
		
	}
	
	//用邮箱发，到时有API就修改该方法业务逻辑
	protected void sendByPhone(PrintWriter writer, String to, String content) {
		Date date=new Date();
		String time=DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
		writer.println(time+"  向手机 "+to+" 发出： "+content );
	}
	//用手机发，到时有API就修改该方法业务逻辑
	protected void seandByEmail(PrintWriter writer, String to, String content) {
		Date date=new Date();
		String time=DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
		writer.println(time+"  向邮箱 "+to+" 发出： "+content );
	}

}
